#include "Timer.h"
#include "EventLoop.h"
#include "Log.h"

namespace dsth {

Timer::Timer(const TimerCallBack& callback, uint64_t duetime, uint64_t period,
             HANDLE timerQueue, EventLoop* loop)
    : callback_(callback),
    timer_(NULL),
    loop_(loop) {
    if (!::CreateTimerQueueTimer(&timer_, timerQueue, 
        (WAITORTIMERCALLBACK)TimerRoutine, this, 
        static_cast<DWORD>(duetime), 
        static_cast<DWORD>(period), 0)) {
        LOG_FATAL("CreateTimerQueueTimer failed (%d)", ::GetLastError());
    }
}

Timer::~Timer() {
    //::DeleteTimerQueueTimer(timer_);
}

VOID CALLBACK Timer::TimerRoutine(PVOID param, BOOLEAN /*TimerOrWaitFired*/) {
    dsth::Timer* timer = (dsth::Timer*)param;
    timer->loop_->RunInLoop(std::make_pair(timer, &Timer::RunTimerCallBack));
}

} // namespace
